package com.fudan.framework.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.apache.commons.beanutils.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fudan.framework.entity.RequestEntity;

/**
 * 实体处理工具
 * @author Xuxinxing
 *
 */
public class EntityUtils {

	private static Logger logger = LoggerFactory.getLogger(EntityUtils.class);
	private static SimpleDateFormat SDF_DATE = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat SDF_TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat SDF_TIMESTAMP = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	private static BeanUtilsBean beanUtilsBean;

	static {
		init();
	}
	public static <T extends RequestEntity> T toEntity(HttpServletRequest request, Class<T> clz) throws Exception {
		Map<String, String[]> parameterMap = request.getParameterMap();
		T bean = clz.newInstance();
		beanUtilsBean.populate(bean, parameterMap);
		return bean;
	}


	public static void init() {
		beanUtilsBean = BeanUtilsBean2.getInstance();
		beanUtilsBean.getConvertUtils().deregister(Date.class);
		beanUtilsBean.getConvertUtils().register(new Converter() {
			@Override
			public <T> T convert(Class<T> type, Object value) {
				return toDate(type, value);
			}
		}, Date.class);
		beanUtilsBean.getConvertUtils().deregister(String.class);
		beanUtilsBean.getConvertUtils().register(new Converter() {
			@Override
			public <T> T convert(Class<T> type, Object value) {
				if (value == null || "".equals(value))
		            return null;
				return (T) value.toString();
			}
		}, String.class);
	}

	@SuppressWarnings("unchecked")
	private static <T> T toDate(Class<T> type, Object value) {
		if (value == null || "".equals(value))
            return null;
		if (value instanceof String) {
            String dateValue = value.toString().trim();
            int length = dateValue.length();
            if (type.equals(Date.class)) {
                try {
                    if (length <= 10) {
                        return (T) SDF_DATE.parse(dateValue);
                    }
                    if (length <= 19) {
                        return (T) SDF_TIME.parse(dateValue);
                    }
                    if (length <= 23) {
                        return (T) SDF_TIMESTAMP.parse(dateValue);
                    }
                } catch (Exception e) {
                	logger.error("",e);
                }
            }
		}
        return (T) value;
	}
}
